package com.maiyuren.fishkit.utils

import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile

object FishFileUtils {
    fun openFile(path: String, mode: String = "r"): RandomAccessFile {
        return RandomAccessFile(path, mode)
    }

    fun seekFile(fileHandler: RandomAccessFile, offset: Long) {
        fileHandler.seek(offset);
    }

    fun readFile(fileHandler: RandomAccessFile, len: Int,  offset: Int = -1): ByteArray {
        val buf = ByteArray(len);
        var read_len = 0;
        if (offset == -1) {
            read_len = fileHandler.read(buf);
        } else {
            fileHandler.seek(offset.toLong());
            read_len = fileHandler.read(buf, 0, len);
        }

        if (read_len == len) {
            return buf;
        }
        return buf.copyOfRange(0, read_len);
    }

    fun closeFile(fileHandler: RandomAccessFile) {
        fileHandler.close();
    }

    fun readAllContent(path: String): ByteArray {
        return File(path).readBytes()
    }

    fun readAllContentOfStringFile(path: String): String {
        return File(path).readText();
    }

    fun readJsonFile(path: String): JSONObject {
        val content = this.readAllContentOfStringFile(path)
        return JSONObject(content);
    }
}